package com.mobimagic.lockscreen.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.mobimagic.lockscreen.AppEnv;
import com.mobimagic.lockscreen.view.MobileChargingScrollView.ScrollInfo;
import com.nineoldandroids.view.ViewHelper;

public class TopFadeView extends View {

    private static final boolean DEBUG = AppEnv.bAppdebug;
    private static final String TAG = "TopFadeView";
    private Paint paint, currentPaint;
    private Bitmap bitmap;
    private LinearGradient linearGradient;
    private Bitmap currentBitmap;
    private Canvas currentCanavs;
    private PorterDuffXfermode shader = new PorterDuffXfermode(Mode.XOR);

    public void setBgBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
        if (isBitampCanDraw(bitmap) && currentCanavs != null) {
            currentCanavs.drawColor(Color.TRANSPARENT, Mode.CLEAR);
            currentCanavs.drawBitmap(bitmap, 0, 0, currentPaint);
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        if (width <= 0 || height <= 0) {
            return;
        }
        if (currentBitmap != null) {
            int bitampWidth = currentBitmap.getWidth();
            int bitmapHeight = currentBitmap.getHeight();
            if (bitampWidth != width || bitmapHeight != height) {
                recyleSafely(currentBitmap);
                currentBitmap = null;
            }
        }
        if (currentBitmap == null) {
            try {
                currentBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                currentCanavs = new Canvas(currentBitmap);
            } catch (NullPointerException e){
                if (DEBUG){
                    Log.e(TAG, "currentBitmap is null");
                }
                currentBitmap = null;
                currentCanavs = null;
            } catch (OutOfMemoryError e) {
                currentBitmap = null;
                currentCanavs = null;
            }
        }
    }

    public TopFadeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        currentPaint = new Paint();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isBitampCanDraw(currentBitmap)) {
            int sc = canvas.saveLayer(0, 0, getMeasuredWidth(), getMeasuredHeight(), null,
                    Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG
                            | Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
            canvas.drawBitmap(currentBitmap, 0, 0, paint);
            paint.setXfermode(shader);
            if (linearGradient == null) {
                linearGradient = new LinearGradient(getMeasuredWidth() / 2, 0, getMeasuredWidth() / 2,
                        getMeasuredHeight(), 0x00000000, 0xff000000, TileMode.CLAMP);
            }
            paint.setShader(linearGradient);
            canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);
            canvas.restoreToCount(sc);
            paint.setShader(null);

        }
        invalidate(0, 0, getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        recyleSafely(currentBitmap);
    }

    private boolean isBitampCanDraw(Bitmap bitamp) {
        if (bitamp == null) {
            return false;
        }
        return !bitamp.isRecycled();

    }

    private void recyleSafely(Bitmap bitamp) {
        if (bitmap == null) {
            return;
        }
        if (bitmap.isRecycled()) {
            return;
        }
        bitmap.recycle();
    }

    public void onScroll(ScrollInfo scrollInfo) {
        int alpha = 0;
        int range = LayoutData.getInstance().getTopFadeHeight();
        int deltaY = (int) (scrollInfo.scrollY - (scrollInfo.scrollTopLine + range));
        if (deltaY > 0) {
            float percent = 1f * deltaY / range;
            alpha = (int) (Math.min(percent, 1) * 255);
            if (DEBUG) {
                Log.d(TAG, "alpha=" + alpha);
            }
        } else {
            alpha = 0;
        }

        ViewHelper.setAlpha(this, alpha / 255f);
    }
}
